import request from '@/utils/request'

// 查询文创商品类别列表
export function listCategory(query) {
  return request({
    url: '/shop/category/list',
    method: 'get',
    params: query
  })
}

// 查询文创商品类别详细
export function getCategory(id) {
  return request({
    url: '/shop/category/' + id,
    method: 'get'
  })
}

// 新增文创商品类别
export function addCategory(data) {
  return request({
    url: '/shop/category',
    method: 'post',
    data: data
  })
}

// 修改文创商品类别
export function updateCategory(data) {
  return request({
    url: '/shop/category',
    method: 'put',
    data: data
  })
}

// 删除文创商品类别
export function delCategory(id) {
  return request({
    url: '/shop/category/' + id,
    method: 'delete'
  })
}

// 生成多层级下拉框数据
export function handleCascader(data, id, name, parentId, children) {
  let config = {
    id: id || 'id',
    name: name || 'name',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    let t = {value: d[config.id], label: d[config.name]}
    nodeIds[d[config.id]] = t;
    childrenListMap[parentId].push(t);
  }
  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      let t = {value: d[config.id], label: d[config.name]}
      tree.push(t);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o.value] !== null) {
      o[config.childrenList] = childrenListMap[o.value];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}
